package pers.wang.toolset.coder.statecode;

import java.util.function.Function;

import pers.wang.toolset.coder.statecode.function.EmptyDataFunction;
import pers.wang.toolset.coder.statecode.state.ServiceStateCode;

public final class StateHelper<R extends CommonResponse<T>, T>{
	private final CommonResponse<T> value;
	private StateHelper() {
		value = null;
	}
	private StateHelper(CommonResponse<T> value) {
		this.value = value;
	}
	public static <T> StateHelper<CommonResponse<T>,T> of(CommonResponse<T> value) {
		return new StateHelper<>(value);
    }
	
	
	@SuppressWarnings("unchecked")
	public <U> StateHelper<?, U> success(Function<T, ? extends CommonResponse<U>> mapper){
		if(ServiceStateCode.SUCCEES.getCode() != value.getState()) {
			return (StateHelper<?, U>) StateHelper.of(value);
		}
		return StateHelper.of(mapper.apply(value.getData()));
	}
	public StateHelper<R, T> empty(EmptyDataFunction function){
		if(ServiceStateCode.EMPTY.getCode() != value.getState()) {
			return this;
		}
		function.apply();
		return this;
	}
	
	public boolean success() {
		return ServiceStateCode.SUCCEES.getCode() == value.getState();
	}
	public CommonResponse<T> get(){
		return this.value;
	}
}
